import * as Ladda from './ladda.js';
$(function(){
	//获取产品
	var selectData = [];
	
	$.ajax({url:"/iotProduct/query",async: false,success:function(result){
		var _data = $.map(result.data.iotProducts, function (obj) {
			obj.text = obj.text || obj.productName; 
			return obj;
		});
		selectData = _data
	}});
	
	//开启select2
	$('.js-data-example-ajax').select2({
		data: selectData
	});
	
	/*value：表示当前单元格中的值
	row：表示当前行
	index：表示当前行的下标*/
	function operateFormatter(value, row, index) {
	    return [
	    	'<button class="btn btn-danger update" data-toggle="modal" data-target="#editModal">编辑</button>  ',
			'<button class="btn btn-danger remove" data-toggle="modal" data-target="#confirmModal">删除</button>'
	    ].join('')
	  }
	
	//当值为0或null时显示无
	function CustomFormatter(value, row, index){
		if(value == 0 || value == null){
			return '无';
		}else{
			return value;
		}
	}
	
	function CustomFormatter2(value, row, index){
		if(value == '' || value == null){
			return 0;
		}else{
			return value.length;
		}
	}
	
	//表格操作
	window.operateEvents = {
		//修改
		'click .update': function (e, value, row, index) {
			console.log(row);
			$("#updateAccountInput").val(row.account);
			$("#updateNameInput").val(row.name);
			$("input:hidden[id='updateId']").val(row.id);
			
			var data = null;
			
			//判断是否有产品
			if(row.iotProductId == 0){
				data = {
					    id: row.iotProductId,
					    text: "无"
					};
			}else{
				data = {
					    id: row.iotProductId,
					    text: row.iotProduct.productName
					};
			}
			
			//如果不存在则创建
			if ($('#updateSelect2').find("option[value='" + data.id + "']").length) {
			    $('#updateSelect2').val(data.id).trigger('change');
			    if(data.id != 0){
			    	$(".disabled-select").prop("disabled", true);
			    }else{
			    	$(".disabled-select").prop("disabled", false);
			    }
			} else {
			    // Create a DOM Option and pre-select by default
			    var newOption = new Option(data.text, data.id, true, true);
			    // Append it to the select
			    $('#updateSelect2').append(newOption).trigger('change');
			} 
		},
		    
		//删除
		'click .remove': function (e, value, row, index) {
			$("input:hidden[id='deleteId']").val(row.id);
			$("#confirmModalMessage").text("确认删除"+row.name+"用户?");
		}
	}
	
	//bootstrap-table配置
	$('#user-tab').bootstrapTable({
	    url: '/user/fingPage',
	    toolbar: "#user-toolbar",
	    toolbarAlign:'right',
	    sidePagination: "server",
	    striped: true, // 是否显示行间隔色
	    pageNumber : 1, 
	    pageSize: 8,
	    pageList: [8, 25],
	    pagination: true, // 是否分页
	    sortable: true, // 是否启用排序
	    queryParams: function(params) {//上传服务器的参数
	        var temp = {
	        	pageNum : this.pageNumber,  
	        	pageSize : this.pageSize,
	        	name : $("#searchName").val(),
	        	account: $("#searchAccount").val(),
	        	productName: $("#searchSelect2").select2("data")[0].productName,
	        };
	        return temp;
	    },
	    columns: [{
	            field: 'name',
	            title: '客户名称',
	            formatter: CustomFormatter
	        },
	        {
	            field: 'iotProduct.productName',
	            title: '所属产品',
	            formatter: CustomFormatter
	        },
	        {
	            field: 'account',
	            title: '账号',
	            formatter: CustomFormatter
	        },
	        {
	            field: 'devicesList',
	            title: '设备个数',
	            formatter: CustomFormatter2
	        },
	        {
	            field: '',
	            title: '操作',
	            align: 'center',
	            valign: 'middle',
	            formatter: operateFormatter,
	            events: window.operateEvents
	        },
	
	    ]
	});
	
	//查询
	$(document).on('click', "#searchBtn",function(){
	     $('#user-tab').bootstrapTable('selectPage', 1, 'refresh');
	     $('#searchModal').modal('hide');
	});
	
	//bootstrapValidator
	$("#userForm")
		.bootstrapValidator({
			message: 'This value is not valid',
			feedbackIcons: {
		        valid: 'glyphicon glyphicon-ok',
		        invalid: 'glyphicon glyphicon-remove',
		        validating: 'glyphicon glyphicon-refresh'
		    },
		    fields: {
		    	account: {
		    		message: '账号验证失败',
		    		validators: {
		    			notEmpty: {
		    				message: '账号不能为空'
		    			}
		    		}
		    	},
		    	name: {
		    		message: '用户名验证失败',
		    		validators: {
		    			notEmpty: {
		    				message: '用户名不能为空'
		    			}
		    		}
		    	},
		    	password: {
		    		message: '密码验证失败',
		    		validators: {
		    			notEmpty: {
		    				message: '密码不能为空'
		    			},
		    			stringLength: {
	                        min: 6,
	                        message: '密码不能少于6位'
	                    },
		    		}
		    	},
		    	passwordAgain: {
		    		message: '确认密码验证失败',
		    		validators: {
		    			notEmpty: {
		    				message: '密码不能为空'
		    			},
	                    identical: {
	                    	field: 'password',
	                        message: '两次密码不一致'
	                    }
		    		}
		    	},
		    	id_count: {
		    		message: '设备个数验证失败',
		    		validators: {
		    			regexp: {
	                        regexp: /^[0-9]*$/,
	                        message: '设备个数只能是数字'
	                    }
		    		}
		    	}
		    }
		})
		.on('success.form.bv', function(e) {
	        // Prevent form submission
	        e.preventDefault();
	
	        // Get the form instance
	        var $form = $(e.target);
	
	        // Get the BootstrapValidator instance
	        var bv = $form.data('bootstrapValidator');
	        
	        // Use Ajax to submit form data
	        var l = Ladda.create(document.querySelector( '#insertBtn' ));
	        $.ajax({
				type: "post",
				url: "/user/insert",
				data: {
					name: $("#nameInput").val(),
					account: $("#accountInput").val(),
					password: $("#passwordInput").val(),
					passwordAgain: $("#passwordAgainInput").val(),
					iotProductId: $("#select2").select2("data")[0].id,
					deviceCount: $("#idCountInput").val()
				},
			 	beforeSend: function () {
			 		$(".ladda-label").text("正在请求服务器");
			 	 	l.start();
			    },
			    complete: function () {
			    	$(".ladda-label").text("确定");
			    	l.stop();
			    },
				success: function(result){
					if(result.code == 0){
						window.location.reload()//刷新当前页面
					}else{
						alert(result.message);
					}
				}
			}) //ajax
			
	    });
	
	
	//修改
	$("#updateBtn").click(function(){
		var l = Ladda.create(this);
		$.ajax({
			type: "post",
			url: "/user/update",
			data: {
				id: $("input:hidden[id='updateId']").val(),
				name: $("#updateNameInput").val(),
				iotProductId: $("#updateSelect2").select2("data")[0].id
			},
			beforeSend: function () {
		 		$(".ladda-update").text("正在请求服务器");
		 	 	l.start();
		    },
		    complete: function () {
		    	$(".ladda-update").text("确定");
		    	l.stop();
		    },
			success: function(result){
				if(result.code == 0){
					window.location.reload()//刷新当前页面
				}else{
					alert("更新失败，请检查");
				}
			}
		})
	})
	
	//删除
	$("#btn-delete").click(function(){
		var l = Ladda.create(this);
		$.ajax({
			type: "post",
			url: "/user/delete",
			data:{id:$("input:hidden[id='deleteId']").val()},
			beforeSend: function () {
		 		$(".ladda-delete").text("正在请求服务器");
		 	 	l.start();
		    },
		    complete: function () {
		    	$(".ladda-delete").text("删除");
		    	l.stop();
		    },
			success: function(result){
				if(result.code == 0){
					window.location.reload()//刷新当前页面
				}else{
					alert("删除失败，请检查");
				}
			}
		})
	})
	
	
	function showLoadingBox(title,message){
	    var html = '<div style="width:100%;position:fixed;left:0;top:30%;z-index:1000;" id="loadingBox">';
	    html += '<div  style="width:30%;margin: 0px auto;">';
	    // var html = '<div class="col-md-6  bg-yellow text-center" style="position:fixed; top:50%;margin: 0px auto;z-index:1000;">';
	    // var html = '<div class="box box-success box-solid" id="loadingBox">';
	    html += '<div class="box box-success box-solid">';
	    html += '<div class="box-header  with-border">';
	    html += '<h3 class="box-title">'+ title + '</h3>';
	    html += '<div class="box-tools pull-right hidden">';
	    html += '<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>';
	    html += '</div>';// <!-- /.box-tools -->
	    html += '</div>';// <!-- /.box-header -->
	    html += '<div class="box-body">' + message+ '</div>';
	            // <!-- /.box-body -->
	            // <!-- Loading (remove the following to stop the loading)-->
	    html += '<div class="overlay">';
	    html += '<i class="fa fa-refresh fa-spin"></i>';
	    html += '</div>'; // <!-- end loading -->
	    html += '</div>'; // <!-- end box -->
	    html += '</div>'; //
	    html += '</div>';
	    $('.content-wrapper').prepend(html);
	    $('#loadingBox [data-widget="remove"]').on('click', function () {
	        $('#loadingBox').remove();
	    });
	}
	
	function hideLoadingBox(timeout, message){
	    if (timeout != undefined && timeout > 0){
	        $('#loadingBox .overlay').remove();
	        $('#loadingBox .box-tools').removeClass('hidden');
	        if (message){
	            $('#loadingBox .box-body').text(message);
	        }
	        setTimeout(() => {
	            $('#loadingBox').remove();
	        }, timeout);
	    }
	    else {
	        $('#loadingBox').remove();
	    }
	}
	
	//导入产品
	$("#importBtn").click(function(){
		showLoadingBox('加载', '正在导入产品...');
		$.ajax({
			type: "get",
			url: "/iotProduct/import",
			success: function(result){
				var data = result.data.iotProducts;
				hideLoadingBox(3000, "成功导入"+data.length+"个产品");
				
	            for (var i in data){
	            	console.log(i)
	            	var attr = "<option value=\"" + data[i].id + "\">" +
	            	data[i].productName + "</option>";
	            	$("#select2").append(attr);
	            	$("#updateSelect2").append(attr);
	            }
			},
			error: function(xhr,status,error){
				console.log("LoadProductList:"+status+",error="+error);
				hideLoadingBox();
			}
		})
	})
})